package com.kang.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.kang.service.FileApiService;
import com.kang.util.FileUtils;
import com.kang.util.GetcontentTypeUtil;
import com.kang.util.OssPropertiesUtils;
import com.kang.util.UpAndDownloadUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class FIleApiServiceImpl implements FileApiService {



    @Override
    public String fileUpload(MultipartFile file) throws IOException {

        String endpoint = OssPropertiesUtils.ALIYUN_OSS_ENDPOINT;
        String accessKeyId = OssPropertiesUtils.ALIYUN_OSS_ACCESSKEYID;
        String accessKeySecret = OssPropertiesUtils.ALIYUN_OSS_SECRET;
        String bucketName = OssPropertiesUtils.ALIYUN_OSS_BUCKET;
        InputStream fileInputStream = null;
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            fileInputStream = file.getInputStream();
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //上传配置实现直接预览
            String type = fileName.substring(fileName.lastIndexOf("."));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(GetcontentTypeUtil.getcontentType(type));
            long timeMillis = System.currentTimeMillis();
            if (".mp4".equals(type)) {
                ossClient.putObject(bucketName, "shipin/" + timeMillis + type, fileInputStream,metadata);
                return "https://" + bucketName + "." + endpoint + "/" + "shipin/" + timeMillis + type ;
            } else {
                ossClient.putObject(bucketName, "tupian/" + timeMillis + type, fileInputStream,metadata);
                return "https://" + bucketName + "." + endpoint + "/" + "tupian/" + timeMillis + type;
            }
            //url https://moyou-yuhongkang.oss-cn-hangzhou.aliyuncs.com/user5-icon.png
        }  catch (IOException e) {
            log.info("获取文件流异常",e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }

    @Override
    public String fileUploadLocal(MultipartFile multiFile) {
        //构建文件对象
        File file = new File(UpAndDownloadUtil.UPLOAD_URL);
        //文件目录不存在则递归创建目录
        if (!file.exists()) {
            boolean mkdirs = file.mkdirs();
            if (!mkdirs) {
                log.error("创建文件夹异常");
                return null;
            }
        }
        try {
            //获取文件输入流
            InputStream inputStream = multiFile.getInputStream();
            String fileName = System.currentTimeMillis() + multiFile.getOriginalFilename();
            //构建文件输出流
            FileOutputStream outputStream = new FileOutputStream(UpAndDownloadUtil.UPLOAD_URL + fileName);
            int copy = FileCopyUtils.copy(inputStream, outputStream);
            log.info("上传成功,文件大小：{}", copy/1000 + "k");
            return fileName;
        } catch (IOException e) {
            log.error("文件上传异常", e);
            return null;
        }

    }

    @Override
    public String videoFileUpload(MultipartFile file) throws IOException {
        String endpoint = OssPropertiesUtils.ALIYUN_OSS_ENDPOINT;
        String accessKeyId = OssPropertiesUtils.ALIYUN_OSS_ACCESSKEYID;
        String accessKeySecret = OssPropertiesUtils.ALIYUN_OSS_SECRET;
        String bucketName = OssPropertiesUtils.ALIYUN_OSS_BUCKET;
        InputStream fileInputStream = null;
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            fileInputStream = file.getInputStream();
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //上传配置实现直接预览
            String type = fileName.substring(fileName.lastIndexOf("."));
            ObjectMetadata metadata = new ObjectMetadata();
            long timeMillis = System.currentTimeMillis();
            metadata.setContentType(GetcontentTypeUtil.getcontentType(type));
            ossClient.putObject(bucketName, "shipin/" + timeMillis + type, fileInputStream,metadata);
            //url https://moyou-yuhongkang.oss-cn-hangzhou.aliyuncs.com/user5-icon.png
            return "https://" + bucketName + "." + endpoint + "/" + "shipin/" + timeMillis + type;
        }  catch (IOException e) {
            log.info("获取文件流异常",e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }

    @Override
    public String fileDownload(HttpServletRequest request, HttpServletResponse response ,String fileName) {

//        String downloadUrl = "https://moyou-yuhongkang.oss-cn-hangzhou.aliyuncs.com/shipin/16735968844161111.mp4";
        String downloadUrl = fileName;
        String downloadPath = "F:\\tmp";
        String downloadFileName = "1234.mp4";  //下载之后的名称
        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        boolean flag = false;
        try {
            URL url = new URL(downloadUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            bis = new BufferedInputStream(connection.getInputStream());
            File file = new File(downloadPath);
            if (!file.exists()) {
                boolean mkdirs = file.mkdirs();
                if (!mkdirs) {
                    log.error("创建文件目录失败");
                    return "创建文件目录失败";
                }
            }
            String filePathName = downloadPath + File.separator + downloadFileName;
            byte[] buf = new byte[1024];
            int size;
            fos = new FileOutputStream(filePathName);
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            log.info("文件下载成功,文件路径[" + filePathName + "]");
            return "文件下载成功";
        } catch (Exception e) {
            log.error("下载文件异常", e);
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                log.error("关流异常", e);
                e.printStackTrace();
            }
        }
        return null;

    }

    @Override
    public String uploadOss(MultipartFile file) throws IOException {
        String endpoint = OssPropertiesUtils.ALIYUN_OSS_ENDPOINT;
        String accessKeyId = OssPropertiesUtils.ALIYUN_OSS_ACCESSKEYID;
        String accessKeySecret = OssPropertiesUtils.ALIYUN_OSS_SECRET;
        String bucketName = OssPropertiesUtils.ALIYUN_OSS_BUCKET;
        InputStream fileInputStream = null;
        OSS ossClient = null;
        try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //上传文件流
            fileInputStream = file.getInputStream();
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //上传配置实现直接预览
            String type = fileName.substring(fileName.lastIndexOf("."));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(GetcontentTypeUtil.getcontentType(type));
            ossClient.putObject(bucketName, "file/" + fileName, fileInputStream,metadata);
            //url https://moyou-yuhongkang.oss-cn-hangzhou.aliyuncs.com/user5-icon.png
            return "https://" + bucketName + "." + endpoint + "/" + "tupian/" + fileName;
        }  catch (IOException e) {
            log.info("获取文件流异常",e);
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
            if (fileInputStream != null) {
                fileInputStream.close();
            }
        }
    }

    @Override
    public List<String> fileUploadListLocal(MultipartFile[] files) throws IOException {

        System.out.println("上传的图片数："+files.length);

        List<String> root=new ArrayList<String>();

        for (MultipartFile file : files) {    //循环保存文件
            root.add(fileUploadLocal(file));
        }
        return root;
    }


}
